package com.wgw.first.cart.adapter;

/**
 * @author Admin
 * @version $Rev$
 * @des ${TODO}
 * @updateAuthor $Author$
 * @updateDes ${TODO}
 */

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.wgw.first.R;
import com.wgw.first.cart.utils.CartStorage;
import com.wgw.first.cart.view.NumberAddSubView;
import com.wgw.first.home.bean.GoodssBean;
import com.wgw.first.utils.Constants;
import com.wgw.first.utils.UpCartData;

import java.util.Iterator;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author Admin
 * @version $Rev$
 * @des ${TODO}
 * @updateAuthor $Author$
 * @updateDes ${TODO}
 */
public class ShopCartAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final Context mcontext;
    private final List<GoodssBean.Goods> datas;
    private final TextView tvShopcartTotal ;
    private CheckBox checkboxAll;
    private CartStorage cartStorage;
    private CheckBox cb_all;



    public ShopCartAdapter(Context context, final List<GoodssBean.Goods> datas, TextView tvShopcartTotal, CheckBox checkboxAll, final CartStorage cartStorage, CheckBox cb_all) {
        this.mcontext = context;
        this.datas = datas;
        this.tvShopcartTotal = tvShopcartTotal;
        this.checkboxAll = checkboxAll;
        this.cartStorage = cartStorage;
        this.cb_all = cb_all;
        setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClickListener(View view, int position) {
                //设置itemview的点击事件
                //根据位置得到对应的对象
                GoodssBean.Goods goodsBean = datas.get(position);

                //设置取反状态
                goodsBean.setSelected(!goodsBean.isSelected());

                CartStorage cartStorage =CartStorage.getInstance(mcontext);
                cartStorage.deleteData(goodsBean);
                cartStorage.addData(goodsBean);
                checkAll();
                //更新
                notifyItemChanged(position);
                //重新计算价格
                showTotalPrice();
                System.out.println("abc"+datas.get(position).toString());
            }
        });
        //设置全选点击事件
        checkboxAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean checked = getCheckboxAll().isChecked();
                checkAll_none(checked);
                showTotalPrice();
            }
        });
        cb_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean checked = getCb_all().isChecked();
                checkAll_none(checked);
                showTotalPrice();
            }
        });

    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(View.inflate(mcontext, R.layout.item_shop_cart, null));
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        //根据位置得到对应的Bean对象
        GoodssBean.Goods goodsBean = datas.get(position);
        //设置数据
        ViewHolder myHolder = (ViewHolder) holder;
        myHolder.setData(goodsBean);

        System.out.println("shopcartAdapter:"+datas);
        showTotalPrice();

    }
    public void showTotalPrice() {
        tvShopcartTotal.setText(getTotalPrice() + "");
    }
    public double getTotalPrice() {
        double total = 0;
        if (datas != null && datas.size() > 0) {
            for (int i = 0; i < datas.size(); i++) {
                GoodssBean.Goods goodsBean = datas.get(i);
                if (goodsBean.isSelected())
                    total += Double.parseDouble(goodsBean.getPrice()) *
                                    Double.parseDouble(goodsBean.getNumber() + "");
            }
        }
        return total;
    }

    @Override
    public int getItemCount() {
        return datas.size();
    }
    public void checkAll_none(boolean checked) {
        if (datas != null && datas.size() > 0) {
            for (int i = 0; i < datas.size(); i++) {
                datas.get(i).setSelected(checked);
                checkboxAll.setChecked(checked);
                notifyItemChanged(i);
            }
        } else {
            checkboxAll.setChecked(false);

        }
    }
    public void checkAll() {
        if (datas != null && datas.size() > 0) {
            for (int i = 0; i < datas.size(); i++) {
                if (!datas.get(i).isSelected()) {
                    checkboxAll.setChecked(false);
                    cb_all.setChecked(false);
                    return;
                } else {
                    checkboxAll.setChecked(true);
                    cb_all.setChecked(true);
                }
            }
        }
    }
    public void deleteData() {
        if (datas != null && datas.size() > 0) {
            for (Iterator iterator = datas.iterator(); iterator.hasNext(); ) {

                GoodssBean.Goods cart = (GoodssBean.Goods) iterator.next();

                if (cart.isSelected()) {

                    //这行代码放在前面
                    int position = datas.indexOf(cart);
                    //1.删除本地缓存的
                    String delete_isbn = cart.getISBN();
                    sendRequestWithOkHttp(mcontext,delete_isbn);
                    cartStorage.deleteData(cart);

                    //2.删除当前内存的
                    iterator.remove();

                    //3.刷新数据
                    notifyItemRemoved(position);

                }
            }
        }
    }
    public void  sendRequestWithOkHttp(final Context context, final String delete_isbn) {
        if(Constants.ALEADYLOGIN==""){
            //如果用户未登录，则不同步数据库
            Toast.makeText(context, "未登录，将在本地数据库操作", Toast.LENGTH_SHORT).show();
        }else{
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        String total = delete_isbn + "@" + Constants.ALEADYLOGIN;
                        System.out.println("delete_isbn:" + delete_isbn);
                        RequestBody requestBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=utf-8"),
                                "total="+total);
                        //                    RequestBody requestBody = new FormBody.Builder()
                        //                            .add("jsoncart",json_cart)
                        //                            .build();
                        OkHttpClient client = new OkHttpClient();
                        Request request = new Request.Builder()
                                .url(Constants.BASE + Constants.DELETESHOPPINGCART)
                                .post(requestBody)
                                .build();
                        Response response = client.newCall(request).execute();
                        String responsedata = response.body().string();
                        System.out.println("delete:responsedata" + responsedata);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }


    private class ViewHolder extends RecyclerView.ViewHolder {

        private CheckBox cbGov;
        private ImageView ivGov;
        private TextView tvDescGov;
        private TextView tvPriceGov;
        private NumberAddSubView numberAddSubView;

        public ViewHolder(View itemView) {
            super(itemView);
            cbGov = (CheckBox) itemView.findViewById(R.id.cb_gov);
            ivGov = (ImageView) itemView.findViewById(R.id.iv_gov);
            tvDescGov = (TextView) itemView.findViewById(R.id.tv_desc_gov);
            tvPriceGov = (TextView) itemView.findViewById(R.id.tv_price_gov);
            numberAddSubView = (NumberAddSubView) itemView.findViewById(R.id.numberAddSubView);

        }
        public void setData(final GoodssBean.Goods goodsBean){
            cbGov.setChecked(goodsBean.isSelected());
            Glide.with(mcontext)
                    .load(Constants.BASE+Constants.IMG+goodsBean.getImgUrl())
                    .into(ivGov);
            tvDescGov.setText(goodsBean.getName());
            tvPriceGov.setText(goodsBean.getPrice());
            numberAddSubView.setValue(goodsBean.getNumber());
            numberAddSubView.setOnNumberChangeListener(new NumberAddSubView.OnNumberChangeListener() {
                @Override
                public void addNumber(View view, int value) {
                    goodsBean.setNumber(value);
                    cartStorage.updataData(goodsBean);
                    showTotalPrice();
                    //上传购物车数据
                    UpCartData.sendRequestWithOkHttp(mcontext);

                }

                @Override
                public void subNumner(View view, int value) {
                    goodsBean.setNumber(value);
                    cartStorage.updataData(goodsBean);
                    showTotalPrice();
                    //上传购物车数据
                    UpCartData.sendRequestWithOkHttp(mcontext);
                }
            });
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onItemClickListener != null) {
                        onItemClickListener.onItemClickListener(v, getLayoutPosition());
                    }
                }
            });
        }

    }
    //回调点击事件的监听
    private OnItemClickListener onItemClickListener;

    interface OnItemClickListener {
        void onItemClickListener(View view, int position);
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }
    public CheckBox getCheckboxAll() {
        return checkboxAll;
    }

    public void setCheckboxAll(CheckBox checkboxAll) {
        this.checkboxAll = checkboxAll;
    }

    public CheckBox getCb_all() {
        return cb_all;
    }

    public void setCb_all(CheckBox cb_all) {
        this.cb_all = cb_all;
    }
}
